package cn.caplike.demo.repository.design.pattern.eventbus.jdk.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@SuppressWarnings("rawtypes")
public class EventBus {
    private static final Map<Class<?>, List<EventListener>> listeners = new ConcurrentHashMap<>();

    public static void register(EventListener listener) {
        listeners.computeIfAbsent(listener.getInterest(), key -> new ArrayList<>()).add(listener);
    }

    public static void unregister(EventListener listener) {
        final List<EventListener> eventListeners = listeners.get(listener.getInterest());
        if (eventListeners != null) {
            eventListeners.remove(listener);
        }
    }

    @SuppressWarnings("unchecked")
    public static void post(Event event) {
        final List<EventListener> eventListeners = listeners.get(event.getClass());
        if (eventListeners != null) {
            for (EventListener listener : eventListeners) {
                listener.handle(event);
            }
        }
    }

    private EventBus() {}
}
